<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('名称')" prop="name">
            <el-input v-model="form.name" :placeholder="$t('名称')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('编码')" prop="code">
            <el-input v-model="form.code" :placeholder="$t('编码')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('Sql脚本')" prop="searchSql">
            <span slot="label">
              {{ $t('Sql脚本') }}
              <el-tooltip placement="top">
                <div slot="content">1.只查询实际值和展示值两个字段,用别名用value和label展示。例(a.id as value)
                  <br>
                  2.预留#{deal_id}  #{fund_id} #{company_id}参数
                  <br>
                  3.如果是联动组件预留参数 #{key}
                </div>
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <textarea ref="searchSql" v-model="form.searchSql" class="codesql" style="height:200px;width:600px;" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="area-header">
        <span style="float: right;font-size: 14px;">
          <template>
            <el-button type="primary" size="mini" @click="getColumnBySql">{{ $t('检查sql') }}</el-button>
          </template>
        </span>
      </div>
      <el-table
        :data="searchResult"
        border
        class="nowrapTable formTable"
      >

        <el-table-column :label="$t('value')" align="center">
          <template slot-scope="scope">
            {{ scope.row.value }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('label')" align="center">
          <template slot-scope="scope">
            {{ scope.row.label }}
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存 取消按钮-->
      <save-btn has-permi="data:fieldData" />
    </div>
  </div>
</template>

<script>
    import { saveOnlCgformFieldData, getOnlCgformFieldData, getByCode, getColumnBySql } from '@/api/system/desform/data/onlCgformFieldData'
    import 'codemirror/theme/ambiance.css'
    import 'codemirror/lib/codemirror.css'
    import 'codemirror/addon/hint/show-hint.css'

    const CodeMirror = require('codemirror/lib/codemirror')
    require('codemirror/addon/edit/matchbrackets')
    require('codemirror/addon/selection/active-line')
    require('codemirror/mode/sql/sql')
    require('codemirror/addon/hint/show-hint')
    require('codemirror/addon/hint/sql-hint')
    export default {
      name: 'CodeMirror',
        data() {
          var validateCode = (rule, value, callback) => {
            if (value && !this.form.id) {
              getByCode(value).then(response => {
                if (response.data) {
                  callback(new Error('该编码已存在'))
                } else {
                  callback()
                }
              })
            } else if (!value) {
              callback(new Error('编码不能为空'))
            } else {
              callback()
            }
          }
            return {
                // 表单参数
                form: {},
                // 遮罩层
                loading: false,
                editor: {},
                // 表单校验
                rules: {
                  code: [{ required: true, validator: validateCode, trigger: 'blur' }],
                  name: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  searchSql: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
                },
               // sql脚本返回的数据
              searchResult: [],
              // 是否已保存
              isAdd: false,
              // 表单配置数据
              onlIndex: 0
            }
        },
        created() {
        },
      mounted() {
        const mime = 'text/x-mariadb'
        // let theme = 'ambiance'//设置主题，不设置的会使用默认主题
        this.editor = CodeMirror.fromTextArea(this.$refs.searchSql, {
          mode: mime, // 选择对应代码编辑器的语言，我这边选的是数据库，根据个人情况自行设置即可
          indentWithTabs: true,
          smartIndent: true,
          lineNumbers: true,
          matchBrackets: true,
          // theme: theme,
          // autofocus: true,
          extraKeys: { 'Ctrl': 'autocomplete' }, // 自定义快捷键
          hintOptions: { // 自定义提示选项
            tables: {
              users: ['name', 'score', 'birthDate'],
              countries: ['name', 'population', 'size']
            }
          }
        })

        this.editor.on('cursorActivity', function() {
          if (this !== null) {
            this.editor.showHint()
          }
        })
      },
        methods: {
            // 初始化数据
            init(data) {
                this.loading = true
                this.searchResult = []
                if (data != null && data.id !== undefined) {
                    getOnlCgformFieldData(data.id).then(response => {
                        this.form = response.data
                      this.editor.setValue(this.form.searchSql !== null ? this.form.searchSql : '')
                        this.loading = false
                    }).catch(() => {
                      this.loading = false
                    })
                } else {
                    this.reset()
                  if (data != null) {
                    this.onlIndex = data.index
                  }
                    this.loading = false
                }
            },
            // 表单重置
            reset() {
                this.form = {
                    id: undefined,
                    name: undefined,
                    code: undefined,
                    searchSql: undefined,
                    delFlag: undefined,
                    createBy: undefined,
                    createTime: undefined,
                    updateBy: undefined,
                    updateTime: undefined
                }
              this.editor.setValue('')
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                // this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                if (this.$parent.$parent.formOpen !== undefined) {
                  this.$parent.$parent.formOpen = false
                }
                // 刷新list页面
                if (this.$parent.$parent.getList !== undefined) {
                  this.$parent.$parent.getList()
                }
                // 刷新表单配置页面 关联数据集合
              if (this.$parent.$parent.getDataSet !== undefined) {
                this.$parent.$parent.getDataSet()
                if (this.isAdd) {
                  this.$parent.$parent.tableData[this.onlIndex].fieldDefaultValue = this.form.code
                }
              }
            },
            /** 提交按钮 */
            submitForm() {
              this.form.searchSql = this.editor.getValue()
                this.$refs['form'].validate(valid => {
                    if (valid) {
                        this.loading = true
                        saveOnlCgformFieldData(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess(this.$t('保存成功'))
                                this.isAdd = true
                                this.closeForm()
                            } else {
                                this.msgError(response.msg)
                            }
                            this.loading = false
                        })
                    } else {
                       this.locationError(document)
                    }
                }).catch(() => {
                    this.loading = false
                })
           },
          // 检查sql
          getColumnBySql() {
            this.searchResult = []
            this.form.searchSql = this.editor.getValue()
            var sql = this.form.searchSql
            if (!this.form.searchSql) {
              this.$message.error('SQL脚本不能为空')
            } else if (!sql.includes('value') || !sql.includes('label')) {
              this.$message.error('SQL脚本不规范,别名缺少 value/label')
            } else {
              getColumnBySql(this.form).then(response => {
                if (response.code === 200) {
                  this.searchResult = response.data.slice(0, 10)
                  this.msgSuccess(this.$t('SQL脚本正常'))
                }
              })
            }
          }
        }
    }
</script>
<style scoped>
</style>
